﻿<template>
	<div class="deviceTemplateInfo-container">
		<el-dialog v-model="isShowDialog" width="90%" draggable="" hight="90%" :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<!--<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>-->
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="ruleForm.id" />
					</el-form-item>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="模板名称" prop="templateName">
							<el-input v-model="ruleForm.templateName" placeholder="请输入模板名称" maxlength="100"
								show-word-limit clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="离线时间" prop="cusdeviceOfflineDecision">
							<el-input-number v-model="ruleForm.cusdeviceOfflineDecision" placeholder="请输入离线时间"
								clearable />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否多从机" prop="multiSlaveMode">
							<el-switch v-model="ruleForm.multiSlaveMode" active-text="是" inactive-text="否" />

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="轮询方式" prop="pollingMethod">
							<el-select clearable v-model="ruleForm.pollingMethod" placeholder="请选择轮询方式">
								<el-option v-for="(item, index) in dl('PollingMethod')" :key="index"
									:value="Number(item.value)"
									:label="`${item.name} (${item.code}) [${item.value}]`"></el-option>

							</el-select>

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态配置" prop="stateConfiguration">
							<el-select clearable v-model="ruleForm.stateConfiguration" placeholder="请选择状态配置">
								<el-option v-for="(item, index) in dl('StateConfiguration')" :key="index"
									:value="Number(item.value)"
									:label="`${item.name} (${item.code}) [${item.value}]`"></el-option>

							</el-select>

						</el-form-item>

					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="操作" prop="stateConfiguration">
							<el-button type="primary" @click="submitNoClose">保存</el-button>
						</el-form-item>

					</el-col>
					
				</el-row>
			</el-form>
			<el-row>
				<el-col :span="24">
					<el-button type="primary" @click="addDeviceTemplate">增加从机</el-button>
					<el-tabs @tab-remove="removeDeviceTemplate" v-model="activeTab">
						<el-tab-pane v-for="(template, index) in deviceTemplates" :key="index"
							:label="template.slaveName" :name="index.toString()" :closable="true">
							<!-- 在这里添加每个设备从机模板的内容 -->
							<el-form-item label="模板名称">
								<el-input v-model="template.slaveName" />
							</el-form-item>
							<device-slave-template-points :deviceSlaveTemplateId="template.id + ''" />
						</el-tab-pane>
					</el-tabs>
				</el-col>
			</el-row>

			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}
</style>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormRules } from "element-plus";
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { getDictLabelByVal as dv } from '/@/utils/dict-utils';
import { addDeviceTemplateInfo, updateDeviceTemplateInfo, detailDeviceTemplateInfo } from "/@/api/Device/Template/deviceTemplateInfo";
import { getAPI } from '/@/utils/axios-utils';
import { SysEnumApi } from '/@/api-services/api';
import { pageDeviceSlaveTemplate, addDeviceSlaveTemplate, deleteDeviceSlaveTemplate } from '/@/api/Device/Template/deviceSlaveTemplate';
import DeviceSlaveTemplatePoints from '/@/views/Device/Template/deviceSlaveTemplatePoints/index.vue'; // 确保路径正确
import { conforms } from "lodash-es";

//父级传递来的参数
var props = defineProps({
	title: {
		type: String,
		default: "",
	},
});
var newIndex = 1;
var deviceTemplateInfoId = "";
//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const ruleFormRef = ref();
const isShowDialog = ref(false);
const ruleForm = ref<any>({});
//自行添加其他规则
const rules = ref<FormRules>({
	cusdeviceOfflineDecision: [{ required: true, message: '请输入离线时间！', trigger: 'blur', },],
	templateName: [{ required: true, message: '请输入模板名称！', trigger: 'blur', },],
});

const activeTab = ref('0');
const deviceTemplates = ref<any>([

]);
// 页面加载时
onMounted(() => {

});
const addDeviceTemplate = async () => {
   //判断 deviceTemplateInfoId是否存在，不存在提示用户先点击保存按钮
	if (!deviceTemplateInfoId) {
		ElMessage.warning('请先保存模板信息');
		return;
	}
	var re = await addDeviceSlaveTemplate({ deviceTemplateInfoId: deviceTemplateInfoId, slaveName: "新从机" + newIndex });
	console.log(re)
	if (re.data.type == "success") {
		await fetchDeviceTemplates();
		//activeTab.value = (deviceTemplates.value.length - 1).toString();
		activeTab.value = (0).toString();
		newIndex++;
		//成功提示
		ElMessage.success('添加模板成功');
	} else {
		ElMessage.warning('添加模板失败:' + re.data.message);
	}
};
// 关闭从机模板的方法
const removeDeviceTemplate = async (index: number) => {
	//询问是否要删除
	ElMessageBox.confirm('是否删除该从机模板?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		// 确认删除
		const templateId = deviceTemplates.value[index].id;
		console.log("要删除的templateId：" + templateId)
		try {
			var re = await deleteDeviceSlaveTemplate({ "id": templateId });
			// deviceTemplates.value.splice(index, 1);
			// if (activeTab.value === index.toString()) {
			// 	activeTab.value = '0';
			// }

			if (re.data.type == "success") {
				ElMessage.success('删除成功');
				deviceTemplates.value.splice(index, 1);
				// 更新 activeTab
				let currentIndex = parseInt(activeTab.value);
				if (currentIndex > index) {
					// 如果当前选中的索引大于删除的索引，当前索引减一
					activeTab.value = (currentIndex - 1).toString();
				} else if (currentIndex === index) {
					// 如果当前索引等于删除的索引，选中第一个标签
					activeTab.value = '0';
				}
				
				//await fetchDeviceTemplates();
			} else {
				ElMessage.error('删除失败');
			}

		} catch (error) {
			ElMessage.error('异常错误：' + error);
		}
	}).catch(() => {
		// 取消删除
	});

};

// 获取设备模板的方法
const fetchDeviceTemplates = async () => {
	try {
		deviceTemplates.value = [];
		const queryParams = {
			deviceTemplateInfoId,
			DescStr: "descending"
		};
		const response = await pageDeviceSlaveTemplate(queryParams);
		deviceTemplates.value = response.data.result.items; // 假设返回的数据在 response.data 中
		console.log(deviceTemplates.value)
	} catch (error) {
		ElMessage.error('获取设备模板失败');
	}
};

// 打开弹窗
const openDialog = async (row: any) => {
	// ruleForm.value = JSON.parse(JSON.stringify(row));
	// 改用detail获取最新数据来编辑
	deviceTemplates.value = [];	
	let rowData = JSON.parse(JSON.stringify(row));
	if (rowData.id)
		ruleForm.value = (await detailDeviceTemplateInfo(rowData.id)).data.result;
	else
		ruleForm.value = rowData;
	isShowDialog.value = true;
	deviceTemplateInfoId = rowData.id;
	// 获取设备模板信息
	if (ruleForm.value.id) {
		await fetchDeviceTemplates();
	}
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	isShowDialog.value = false;
};

// 取消
const cancel = () => {
	isShowDialog.value = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = ruleForm.value;
			values.deviceSlaveTemplates = deviceTemplates.value;
			if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
				 await addDeviceTemplateInfo(values);
			} else {
				await updateDeviceTemplateInfo(values);
			}
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
	
};
// 提交
const submitNoClose = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = ruleForm.value;
			values.deviceSlaveTemplates = deviceTemplates.value;
			if (ruleForm.value.id == undefined || ruleForm.value.id == null || ruleForm.value.id == "" || ruleForm.value.id == 0) {
			var res=await addDeviceTemplateInfo(values);
			deviceTemplateInfoId=res.data.result;
			}  else {
				await updateDeviceTemplateInfo(values);
			}
			ElMessage.success('成功');

		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
	
};





//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
